package com.juc.learn.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName:LShareNumber
 * Package:com.juc.learn.lock
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/7/26 - 16:52
 * @Version:v1.0
 */
public class LShareNumber {
    private int number=0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void add() throws InterruptedException {
        lock.lock();
        try {
            while (number!=0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"执行了add方法，当前number的值为："+number++);
            condition.signalAll();//唤醒别的线程
        }finally {
            lock.unlock();
        }
    }
    public void sub() throws InterruptedException {
        lock.lock();
        try {
            while (number==0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"执行了sub方法，当前number的值为："+number--);
            condition.signalAll();//唤醒别的线程

        }finally {
            lock.unlock();
        }
    }


}
